//
//  WBStatusListViewModel.swift
//  仿写微博
//
//  Created by Apple on 17/7/16.
//  Copyright © 2017年 tuimao. All rights reserved.
//

import UIKit
import SDWebImage
/*微博的视图模型：
 1.字典转模型
 2.下拉/上拉刷新
 */
class WBStatusListViewModel{
    lazy var statusList = [WBStatusViewModel]()
    //最大上拉次数
    let maxPullupTryTime = 3
    //已尝试刷新次数
    var pullupErrorTimes = 0
    
    //
    /// 记载微博列表
    ///pullup :是否是上拉刷新
    /// - Parameter completion: 完成回调，判断成功和是否有更多的下拉数据
    func loadStatus(pullup:Bool,completion:@escaping (_ issuccess:Bool,_ shouldRefrsh:Bool)->()){
        
        
        //判断上拉或者下拉数据
        let since_id = pullup ? 0 : statusList.first?.status.id ?? 0
        let max_id = !pullup ? 0 : statusList.last?.status.id  ?? 0
        //判断是否进入到上拉刷新的最大限制
        if pullup && self.pullupErrorTimes > self.maxPullupTryTime {
            print("上拉没有数据")
            completion(true, false)
            return 
        }
        
        // 让数据访问层加载数据
        WBStatusListDAL.loadStatus(since_id: since_id, max_id: max_id) { (list, isSuccess) in
            //判断是否成功
            if !isSuccess {
                completion(false, false)
            }
            //创建模型的可变数组
            var array = [WBStatusViewModel]()
            //遍历数组 并把字典转化成模型（并不是转化成模型数组）
            for dict in list ?? [] {                
                guard let model = WBStatus.yy_model(with: dict)else{
                    continue
                }
                //添加到模型数组中
                array.append(WBStatusViewModel(model: model))
            }
            if pullup {
                self.statusList += array
            }else{
                //添加到数组
            self.statusList = array + self.statusList
            }
            if pullup && array.count == 0  { //当刷新到没有数据时候
                self.pullupErrorTimes += 1
                completion(isSuccess, false)
            }else{  //还有数据的时候
                //缓存单张的图片 并完成回调
                self.cacheSingleImage(list: array, finish: completion)
                
            }
        }
    }
    
    /// 缓存本次下载微博数据的单张图片
    ///
    /// - Parameter list: 下载的视图模型数组
    private func cacheSingleImage(list:[WBStatusViewModel],finish:@escaping (_ issuccess:Bool,_ shouldRefrsh:Bool)->()){
        //记录数据长度
        var lenth = 0
        //调度组
        let group = DispatchGroup()
        for vm in list {
            if vm.picURLs?.count != 1{
                continue
            }
            guard let pic = vm.picURLs?[0].thumbnail_pic,
                  let url = URL(string: pic)else{
                    continue
            }
            //入组
            group.enter()
            //下载缓存的单张图片
            _ = SDWebImageManager.shared().imageDownloader?.downloadImage(with: url, options: [], progress: nil
                , completed: { (image, _, _, _) in
                    guard let image = image,
                        let data = UIImagePNGRepresentation(image)else{
                            return
                    }
                    lenth += data.count
                    //设置缓存单张图片的大小
                    vm.updateSingleImageSize(image: image)
                    //出组
                    group.leave()
            })
        }
        //监听调度组
        group.notify(queue: DispatchQueue.main) { 
            //完成回调
            finish(true, true)
             print("缓存的图片大小:\(lenth / 1024)kb")
        }
    }
}
